package com.dtw.ditouwang.ui.more;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dtw.ditouwang.R;
import com.dtw.ditouwang.beans.CommonBean;
import com.dtw.ditouwang.repositories.UserRepository;
import com.dtw.ditouwang.ui.BaseActivity;
import com.dtw.ditouwang.ui.OnItemClickListener;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SendCommentActivty extends BaseActivity implements View.OnClickListener, OnItemClickListener {
    private final int CodeCamera = 100,CodePicture=101;
    private TextView textLeftcount;
    EditText content;
    private RecyclerView recyclerview;
    SendCommentImageAdapter sendCommentImageAdapter;
    List<Bitmap> bitmapList = new ArrayList<>();
    List<String> uploadedPathList = new ArrayList<>();
    AlertDialog takePic;
    Spinner spinner;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_comment);
        initView();
        enableBack();
        setTitle("发帖");
        setSubTitle("发布", this);

        sendCommentImageAdapter = new SendCommentImageAdapter(bitmapList);
        sendCommentImageAdapter.setOnItemClickListener(this);
        recyclerview.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerview.setAdapter(sendCommentImageAdapter);
    }

    private void initView() {
        textLeftcount = findViewById(R.id.text_leftcount);
        recyclerview = findViewById(R.id.recyclerview);
        content = findViewById(R.id.edit_conent);
        spinner = findViewById(R.id.spinner);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_sub_title:
                if(bitmapList.size()==0){
                    showToast("请拍照");
                    return;
                }
                sendComment();
                break;
            case R.id.text_camera:
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CodeCamera);
                takePic.dismiss();
                break;
            case R.id.text_picture:
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, CodePicture);
                takePic.dismiss();
                break;
            case R.id.text_cancle:
                if (takePic != null && takePic.isShowing()) {
                    takePic.dismiss();
                }
                break;
            case R.id.sendButton:
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CodeCamera:
                    Bundle extras = data.getExtras();
                    Bitmap bitmap = (Bitmap) extras.get("data");
                    bitmapList.add(bitmap);
                    sendCommentImageAdapter.notifyDataSetChanged();
                    break;
                case CodePicture:
                    Uri selectedImage = data.getData();
                    try {
                        Bitmap pic  = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
                        bitmapList.add(pic);
                        sendCommentImageAdapter.notifyItemInserted(bitmapList.size()-1);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    AlertDialog alertDialog;
    private void sendComment() {
        alertDialog = new AlertDialog.Builder(this, R.style.Dialog).setView(new ProgressBar(this)).show();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.getWindow().setDimAmount(0);
        if (bitmapList.size() > 0) {
            Bitmap bitmap = bitmapList.get(0);
            try {
                File imgFile = new File(getExternalFilesDir(Environment.DIRECTORY_DCIM), System.currentTimeMillis() + ".jpg");
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imgFile));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
                final RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), imgFile);
                MultipartBody.Part filePart = MultipartBody.Part.createFormData("imged", imgFile.getName(), requestFile);
                webApi.uploadImage(filePart).enqueue(new Callback<CommonBean>() {
                    @Override
                    public void onResponse(Call<CommonBean> call, Response<CommonBean> response) {
                        if (response.body().isResult()&&!isFinishing()) {
                            uploadedPathList.add((String) response.body().getData());
                            bitmapList.remove(0);
                            sendComment();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonBean> call, Throwable t) {

                    }
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            String imgPaths = "";
            for (String imgPath : uploadedPathList) {
                if (imgPaths.length() < 1) {
                    imgPaths = imgPath;
                } else {
                    imgPaths += ","+ imgPath;
                }
            }
            webApi.sendArt(UserRepository.getInstance().getUserID(),spinner.getSelectedItemPosition()+1, content.getText().toString(), imgPaths).enqueue(new Callback<CommonBean>() {
                @Override
                public void onResponse(Call<CommonBean> call, Response<CommonBean> response) {
                    if (response.body().isResult()&&!isFinishing()) {
                        if (alertDialog != null && alertDialog.isShowing()) {
                            alertDialog.dismiss();
                        }
                        showToast("发帖成功");
                        finish();
                    }
                }

                @Override
                public void onFailure(Call<CommonBean> call, Throwable t) {
                        if (alertDialog != null && alertDialog.isShowing()) {
                            alertDialog.dismiss();
                        }
                        showToast("网络异常");
                }
            });
        }
    }

    @Override
    public void onItemClick(int viewID, final int position, int state) {
        if (position == bitmapList.size()) {
            View view = LayoutInflater.from(this).inflate(R.layout.dialog_choose_image, null);
            takePic = new AlertDialog.Builder(this, R.style.BottomDialog).setView(view).show();
            Window window = takePic.getWindow();
            window.setGravity(Gravity.BOTTOM); // 此处可以设置dialog显示的位置
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            view.findViewById(R.id.text_camera).setOnClickListener(this);
            view.findViewById(R.id.text_picture).setOnClickListener(this);
            view.findViewById(R.id.text_cancle).setOnClickListener(this);
        }else{
            new AlertDialog.Builder(this).setTitle("删除这张照片？")
                    .setNegativeButton("否",null)
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            bitmapList.remove(position);
                            sendCommentImageAdapter.notifyItemRemoved(position);
                        }
                    })
                    .show();
        }
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this).setTitle("离开发帖页面")
                .setNegativeButton("否",null)
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SendCommentActivty.super.onBackPressed();
                    }
                }).show();
    }
}